package de.lmu.ifi.pst.uwejsf.framework;

import javax.script.ScriptContext;
import javax.script.ScriptEngine;

public class OGNLNavigationPropertyResolver implements
		NavigationPropertyResolver {

	private Expression expression;
	private Object storedValue;
	private long lastEvaluationToken = Long.MIN_VALUE;

	@Override
	public Expression getExpression() {
		return expression;
	}

	@Override
	public Object getValue(ExpressionContextProvider contextProvider,
			String nodeName, String propertyName, Object contentObject) {
		long currentEvaluationToken = AbstractUWENavigator.getNavigator()
				.getEvaluationToken();
		if (currentEvaluationToken == lastEvaluationToken) {
			return storedValue;
		}
		if (expression == null)
			return null;
		if (expression.getExpression() == null)
			return null;

		ScriptEngine engine = contextProvider.getScriptEngineByName("ognl");
		ScriptContext scriptContext = contextProvider
				.createScriptContext(contentObject);
		Object result = null;
		try {
			result = engine.eval(expression.getExpression(), scriptContext);
		} catch (Exception e) {
			throw new NavigationException("Couldn't evaluate OGNL script: "
					+ expression.getExpression(), e);
		}
		storedValue = result;
		lastEvaluationToken = currentEvaluationToken;

		return result;
	}

	@Override
	public void setExpression(Expression expression) {
		this.expression = expression;

	}

}
